<script setup>
	import { ref, onMounted, watchEffect } from "vue"
	
	let props = defineProps({
		'modelValue': null,
		'type': {
			type: String,
			default: 'selector'
		},
		data: {
			type: Array,
			default: []
		},
		placeholder: String
	})
	
	let emit = defineEmits(['update:modelValue'])
	
	let label = ref('')
	let  bindPickerChange = (e) => {
		if (props.type == 'selector') {
			label.value = props.data[e.detail.value].label
			emit('update:modelValue', props.data[e.detail.value].value)
		}
		if (props.type == 'date') {
			label.value = e.detail.value
			emit('update:modelValue', e.detail.value)
		}
	}
	
	watchEffect(() => {
		if (props.type == 'selector') {
			let item = props.data.find(item => item.value == props.modelValue)
			if (item) label.value = item.label
			else label.value = ''
		}
		if (props.type == 'date') {
			label.value = props.modelValue
		}
	})
	
	onMounted(() => {
	})
</script>

<template>
	<picker :mode="type" :range="data" range-key="label" @change="bindPickerChange">
		<view class="rong-qi">
			<text v-if="label">{{ label }}</text>
			<text v-else class="placeholder">{{ placeholder ?? '请选择' }}</text>
			<uni-icons type="right" color="#999999" size="15"></uni-icons>
		</view>
	</picker>
</template>

<style scoped>
	.rong-qi {
		display: flex;
		align-items: center;
	}
	.placeholder {
		color: #999999;
	}
</style>